#include "Thread.h"

#include <iostream>
#include <unistd.h>
#include <exception>
#include <sys/types.h>
#include <sys/syscall.h>

namespace sevent{

Thread::Thread(const ThreadFunc &init, const ThreadFunc &run, const ThreadFunc &stop)
: _started(false), _pid(0), _tid(0), _initFunc(init), _runFunc(run), _stopFunc(stop){
}

Thread::~Thread(){
}

void *Thread::startRoutine(void *thread){
	Thread *t = static_cast <Thread *>(thread);
	int ret = 0;
	try{
		ret = t->_initFunc();
	}catch(std::exception &e){
		std::cerr << "Thread::_initFunc exception: " << e.what() << std::endl;
	}
	t->setInitRet(ret); 
	try{
		t->_runFunc();
	}catch(std::exception &e){
		std::cerr <<"Thread::_runFunc exception: " << e.what() << std::endl;
	}
	return NULL;
}

void Thread::start(){
	_started = true;
	if (pthread_create(&_tid, NULL, startRoutine, this)) {
		std::cerr << "pthread create error." << std::endl;
	}
	return;
}

int Thread::wait(){
	return pthread_join(_tid, NULL);
}

int Thread::stop(){
	_started = false;
	return pthread_join(_tid, NULL);
}


}

